package edu.gmu.tec.notif;

import edu.gmu.tec.scout.udp.BroadcastWrapper;
import edu.gmu.tec.scout.utilities.Encryption;
import edu.gmu.tec.scout.utilities.SimpleXMLSerializer;
import android.os.Parcel;
import android.os.Parcelable;

public class ParcelableBroadcastWrapper implements Parcelable{
	private Encryption encryption;
	private SimpleXMLSerializer<BroadcastWrapper> serializer;

	private BroadcastWrapper wrapper;

	ParcelableBroadcastWrapper(BroadcastWrapper wrapper){
		this.wrapper = wrapper;
	}
	
	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel out, int flags) {

		try{
			//serialize into bytes for encryption and transport
			byte[] bytes = serializer.serialize(wrapper);
			
			//encrypt bytes
			byte[] cipertext = encryption.encrypt(bytes);
			
			//write the bytes out to a byte array for transport
			out.writeByteArray(cipertext);
		}catch(Exception e){

		}


	}

	public static final Parcelable.Creator<ParcelableBroadcastWrapper> CREATOR
	= new Parcelable.Creator<ParcelableBroadcastWrapper>() {

		public ParcelableBroadcastWrapper createFromParcel(Parcel in) {
			return new ParcelableBroadcastWrapper(in);
		}

		public ParcelableBroadcastWrapper[] newArray(int size) {
			return new ParcelableBroadcastWrapper[size];
		}
	};

	private ParcelableBroadcastWrapper(Parcel in) {
		//TODO: dynamically determine byte array size
		try{
			//create byte array for the cipertext
			byte[] ciphertext = new byte[1500];
			
			//read the cipertext into the byte array from the parcel
			in.readByteArray(ciphertext);

			//decrypt ciphertext
			byte[] plaintext = encryption.decrypt(ciphertext);
			
			//deserialize back into a the Broadcast wrapper
			wrapper = serializer.deserialize(BroadcastWrapper.class, plaintext);
			
		}catch (Exception e){

		}
	}

	public BroadcastWrapper getBroadcastWrapper(){
		return wrapper;
	}

}
